//
//  CommentViewController.m
//  FlickrSearching
//
//  Created by admin on 4/25/15.
//  Copyright (c) 2015 HOCVIEN. All rights reserved.
//

#import "CommentViewController.h"
#import "CommentTableViewCell.h"
#import "FlickrHelper.h"
@interface CommentViewController ()<UITableViewDataSource, UITableViewDelegate, UISearchControllerDelegate, UISearchDisplayDelegate, UIAlertViewDelegate>
@property (nonatomic, strong) NSArray *commentList;
@property (nonatomic, strong) NSString *stringSearch;
@property (nonatomic, strong) NSArray *commentSearch;

@end

@implementation CommentViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.tbvCommentList.delegate = self;
    self.tbvCommentList.dataSource = self;
    
    self.searchDisplayController.searchResultsDataSource=self;
    self.searchDisplayController.searchResultsDelegate = self;
    self.commentSearch = [[NSArray alloc]init];
    [self loadData2];
}
- (void)loadData2{
    UIActivityIndicatorView *activity = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake((self.view.frame.size.width - 20) /2, (self.view.frame.size.height - 20) /2, 20, 20)];
    [activity startAnimating];
    [FlickrHelper getCommentsWithPhotosSetId:self.photoSetID callback:^(NSArray *result, NSError *error) {
        if (result.count > 0 && !error) {
            self.commentList = result;
            [self.tbvCommentList reloadData];
            
        }else{
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Thông báo" message:[NSString stringWithFormat:@"Hiện không thể load được dữ liệu! Bạn có muốn thử lại không?"] delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", nil];
            [alert show];
        }
        [activity stopAnimating];
    }];
}
- (void)loadData{
    NSLog(@"%@",self.commentList);
   // NSPredicate *pre = [NSPredicate predicateWithFormat:@"%K contains[c]",@"authorname",self.stringSearch];
    NSPredicate *pre2 = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        NSString *name =[evaluatedObject objectForKey:@"_content"];
        
        if([[name lowercaseString] containsString:[self.stringSearch lowercaseString]]) {
            return YES;
            } else {
                return NO;
            }
    }];
    self.commentSearch = [self.commentList filteredArrayUsingPredicate:pre2];
    [self.searchDisplayController.searchResultsTableView reloadData];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        [self loadData2];
    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark TableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *cellID = @"comment_cell_id";
    
    CommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell ) {
        [tableView registerClass:[CommentTableViewCell class] forCellReuseIdentifier:cellID];
        cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    }
    NSDictionary *comment;
    if (self.stringSearch) {
        cell = [self.tbvCommentList dequeueReusableCellWithIdentifier:cellID];
        comment = [self.commentSearch objectAtIndex:indexPath.row];
    }else{
        comment = [self.commentList objectAtIndex:indexPath.row];
    }
    
    if (!(indexPath.row %2)) {
        [cell setBackgroundColor:[UIColor colorWithRed:247/255.f green:238/255.f blue:249/255.f alpha:1]];
    }else{
        [cell setBackgroundColor:[UIColor colorWithRed:250/255.f green:248/255.f blue:250/255.f alpha:1]];
    }
    cell.imvComment.image = [UIImage imageNamed:@"thumbnail-default.jpg"];
    
    cell.lblName.text = [comment objectForKey: @"authorname"];
    cell.lblCommentContent.text = [comment objectForKey:@"_content"];
    return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.stringSearch) {
        return self.commentSearch.count;
    }
    return [self.commentList count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 108;
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{
    self.stringSearch = searchString;
    [self loadData];
    
    return YES;
}

@end
